package com.asura.app.wechat.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

import com.asura.app.wechat.utils.UIUtils;

/**
 * Created by Asura on 2017/12/28.
 */

public class AutoSizeImageView extends NetworkImageView {

    private int maxSize;

    public AutoSizeImageView(Context context) {
        this(context, null);
    }

    public AutoSizeImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoSizeImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        maxSize = UIUtils.getScreenWidth(getContext()) / 2;
        setAdjustViewBounds(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredHeight = getMeasuredHeight();
        int measuredWidth = getMeasuredWidth();
        int realWidth = measuredWidth;
        int realHeight = measuredHeight;
        if (measuredHeight > 0 && measuredWidth > 0) {
            if (measuredWidth > measuredHeight && measuredWidth > maxSize) {
                realWidth = maxSize;
                realHeight = (int) (maxSize * 1.0f / measuredWidth * measuredHeight);
            } else if (measuredHeight > measuredWidth && measuredHeight > maxSize) {
                realHeight = maxSize;
                realWidth = (int) (maxSize * 1.0f / measuredHeight * measuredWidth);
            }
        }
        setMeasuredDimension(realWidth, realHeight);
    }
}
